package com.yxw.yxnet_cd_center.customer_service.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FastByteArrayOutputStream;
import com.yxw.yxnet_cd_center.common.constant.RedisIdConstant;
import com.yxw.yxnet_cd_center.common.dto.BaseDTO;
import com.yxw.yxnet_cd_center.common.enums.CommonErrorEnum;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.BaseResult;
import com.yxw.yxnet_cd_center.customer_service.dto.RefreshTokenDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.UserLoginDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.UserPhoneLoginDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.UserSendCodeDTO;
import com.yxw.yxnet_cd_center.customer_service.service.LoginService;
import com.yxw.yxnet_cd_center.customer_service.utils.RedisManager;
import com.yxw.yxnet_cd_center.customer_service.vo.LoginUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * 登录管理
 * @author liuxin
 * @date 2023.09.12
 */
@RestController
@CrossOrigin
@Api(value = "登录管理", tags = "登录管理")
@Slf4j
@RequestMapping("/logon")
public class LoginController {

    @Resource
    private RedisManager redisManager;

    @Autowired
    private LoginService loginService;


    /**
     * 生成随机验证码图片
     * @param response 响应
     */
    @ApiOperation(value = "生成随机验证码图片")
    @PostMapping(value = "/v1/validateImage")
    public BaseResult<String> validateImage(HttpServletResponse response) {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 69, 4, 0);
        String uuid = UUID.randomUUID().toString();
        Cookie clientKey = new Cookie("clientKey", uuid);
        clientKey.setPath("/");
        response.addCookie(clientKey);
        redisManager.set(RedisIdConstant.LOGIN_PICTURE_CODE + uuid, captcha.getCode(), 300L);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try{
            ImageIO.write(captcha.getImage(), "png", os);
        }catch (IOException e){
            log.error(e.getMessage());
            throw new BaseException(CommonErrorEnum.QRCODE_ERROR);
        }
        return BaseResult.doSuccess(Base64.encode(os.toByteArray()),"生成验证码成功");
    }

    @ApiOperation(value = "账号密码登录")
    @PostMapping("/v1/login")
    public BaseResult<LoginUserVo> login(@Validated @RequestBody UserLoginDTO userLoginDTO, @CookieValue(value="clientKey",required=false) String clientKey) throws Exception {
        String captcha = (String) redisManager.get(RedisIdConstant.LOGIN_PICTURE_CODE + clientKey);
        redisManager.del(RedisIdConstant.LOGIN_PICTURE_CODE + clientKey);
        if(!userLoginDTO.getVerificationCode().equals(captcha)){
            throw new BaseException(CommonErrorEnum.INCORRECT_VERIFICATION_CODE);
        }
        LoginUserVo loginUserVo = loginService.login(userLoginDTO);
        return BaseResult.doSuccess(loginUserVo,"登录成功");
    }

    /**
     * 手机号验证码获取
     */
    @ApiOperation(value = "手机号验证码获取")
    @PostMapping("/v1/send")
    public BaseResult send(@Validated @RequestBody UserSendCodeDTO userSendCodeDTO){
        loginService.send(userSendCodeDTO);
        return BaseResult.doSuccess("","发送成功");
    }

    /**
     * 手机号验证码登录
     */
    @ApiOperation(value = "手机号验证码登录")
    @PostMapping("/v1/phone")
    public BaseResult<LoginUserVo> phone(@Validated @RequestBody UserPhoneLoginDTO userPhoneLoginDTO, @CookieValue(value="clientKey",required=false) String clientKey) {
        String captcha = (String) redisManager.get(RedisIdConstant.LOGIN_PICTURE_CODE + clientKey);
        redisManager.del(RedisIdConstant.LOGIN_PICTURE_CODE + clientKey);
        if(!userPhoneLoginDTO.getVerificationCode().equals(captcha)){
            throw new BaseException(CommonErrorEnum.INCORRECT_VERIFICATION_CODE);
        }
        LoginUserVo loginUserVo = loginService.phone(userPhoneLoginDTO);
        return BaseResult.doSuccess(loginUserVo,"登录成功");
    }

    @ApiOperation(value = "系统登出")
    @PostMapping("/v1/logout")
    public BaseResult logout(@Validated @RequestBody BaseDTO baseDTO){
        loginService.logout(baseDTO);
        return BaseResult.doSuccess(null,"注销成功");
    }


    @ApiOperation(value = "刷新token接口")
    @PostMapping("/v1/refreshToken")
    public BaseResult<LoginUserVo> refreshToken(HttpServletRequest request)  {
        LoginUserVo loginUserVo=loginService.refreshToken(request);
        return BaseResult.doSuccess(loginUserVo,"刷新token成功");
    }
}
